package com.xcode.xandrdb.sqlite;

import java.util.List;

import com.xcode.xandrdb.Factory.SessionFactory;
import com.xcode.xandrdb.Session.SessionApplication;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.Message;

public class SqliteHelper extends SQLiteOpenHelper
{
	private final int BASH_EXECUTE = 1;
	private Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			Object object = msg.obj;
			switch (msg.what)
			{
			case BASH_EXECUTE:
			{
				try
				{

					String[] sqls = (String[]) object;
					writableDatabase.beginTransaction();
					for (int i = 0; i < sqls.length; i++)
					{
						String sql = sqls[i];
						writableDatabase.execSQL(sql);
					}
					writableDatabase.setTransactionSuccessful();

				} catch (Exception e)
				{
					e.printStackTrace();
				} finally
				{
					writableDatabase.endTransaction();
				}
			}
				break;
			default:
				break;
			}
		};
	};
	private static SqliteHelper helper = null;
	private SQLiteDatabase writableDatabase = null;
	private SQLiteDatabase readableDatabase = null;

	private SqliteHelper(Context context, String name, CursorFactory factory, int version)
	{
		super(context, name, factory, version);
	}

	public synchronized static SqliteHelper getInstance()
	{
		if (helper == null)
		{
			helper = new SqliteHelper(SessionApplication.getInstance(), SessionFactory.getConfig().DB_Name, null, 1);
			helper.writableDatabase = helper.getWritableDatabase();
			helper.readableDatabase = helper.getReadableDatabase();
		}
		return helper;
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{

	}

	public void execSQL(String sql)
	{
		writableDatabase.execSQL(sql);
	}

	public Cursor rawQuery(String sql, String[] selectionArgs)
	{
		return readableDatabase.rawQuery(sql, selectionArgs);
	}

	public void bashExecSQL(String[] sqls)
	{
		Message message = handler.obtainMessage();
		message.what = BASH_EXECUTE;
		message.obj = sqls;
		handler.sendMessage(message);
	}

	public void bashExecSQL(List<String> list)
	{
		bashExecSQL(list.toArray(new String[list.size()]));
	}

	public void close(Object object)
	{
		//
	}
}
